﻿using System.Collections;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

namespace E.Tool
{
    public abstract class UIList<T> : MonoBehaviour
    {
        [SerializeField] protected Transform parent;
        [SerializeField] protected GameObject prefab;
        [SerializeField] protected List<T> datas = new List<T>();

        public List<T> Datas { get => datas; }

        protected virtual void Awake()
        {
            Refresh();
        }

        public void SetData(List<T> datas)
        {
            this.datas = datas;
            Refresh();
        }
        public virtual void Refresh()
        {
            for (int i = 0; i < parent.childCount; i++)
            {
                parent.GetChild(i).gameObject.SetActive(false);
            }

            if (datas == null)
                return;

            foreach (T item in datas)
            {
                GameObject go = GetAvailableSlot();
                UISlot<T> slot = go.GetComponent<UISlot<T>>();
                slot.SetData(item);
            }
        }
        protected GameObject GetAvailableSlot()
        {
            GameObject go;
            for (int i = 0; i < parent.childCount; i++)
            {
                if (parent.GetChild(i).gameObject.activeInHierarchy)
                    continue;

                go = parent.GetChild(i).gameObject;
                go.SetActive(true);
                return go;
            }
            go = Instantiate(prefab.gameObject, parent);
            go.SetActive(true);
            return go;
        }
    }
}